package com.icesoft.base.manager.security.login.handle;


import com.icesoft.base.manager.entity.system.SysUserLoginRecord;
import com.icesoft.base.manager.helper.AuthUser;
import com.icesoft.base.manager.security.login.phone.PhoneAuthenticationToken;
import com.icesoft.base.manager.security.suppose.IUserDetailsService;
import com.icesoft.base.manager.service.system.SysUserLoginRecordService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
@Slf4j
public class LoginFailureRecordEventListener implements ApplicationListener<AbstractAuthenticationFailureEvent> {
    private SysUserLoginRecordService sysUserLoginRecordService;
    private IUserDetailsService userDetailsService;

    @Override
    public void onApplicationEvent(AbstractAuthenticationFailureEvent event) {
        Authentication authentication = event.getAuthentication();
        SysUserLoginRecord sysUserLoginRecord = new SysUserLoginRecord();
        WebAuthenticationDetails details = (WebAuthenticationDetails) event.getAuthentication().getDetails();
        sysUserLoginRecord.setLoginIp(details.getRemoteAddress());
        sysUserLoginRecord.setLoginSuccess(false);
        sysUserLoginRecord.setUsername(authentication.getName());
        UserDetails userDetails = null;
        try {
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                userDetails = userDetailsService.loadUserByUsername(authentication.getName());
            }
            if (authentication instanceof PhoneAuthenticationToken) {
                userDetails = userDetailsService.loadUserByPhone(authentication.getName());
            }
        } catch (UsernameNotFoundException e) {
            log.trace("username not found:[{}]", authentication.getName());
        }
        if (userDetails != null && userDetails instanceof AuthUser) {
            sysUserLoginRecord.setUserId(((AuthUser) userDetails).getId());
        }

        sysUserLoginRecord.setErrorMsg(event.getException().getMessage());
        sysUserLoginRecordService.create(sysUserLoginRecord);
    }
}
